#! /usr/bin/python

import os
import os.path

__author__="ken"
__date__ ="$2009-2-4 16:26:31$"


def sendFile(outfile, socket, offset = 0, size = 0, bufsize = 1024):
    assert offset >= 0
    assert size >= 0
    assert bufsize > 0
    assert outfile and socket

    outfile.seek(offset, os.SEEK_SET)
    if size == 0: # send all
        while True:
            buf = outfile.read(bufsize)
            if not buf:
                return
            else:
                socket.send(buf)
    else:
        while size / bufsize > 0:
            buf = outfile.read(bufsize)
            if not buf:
                return
            if len(buf) < bufsize:
                socket.send(buf)
                return
            size -= bufsize
        assert size >=0 and size < bufsize
        if size == 0: return
        buf = outfile.read(size)
        if buf:
            socket.send(buf)
        return

def recvFile(infile, socket, offset = 0, size = 0, bufsize = 1024):
    assert offset >= 0
    assert bufsize > 0
    assert infile and socket

    infile.seek(offset, os.SEEK_SET)
    if size == 0:
        while True:
            buf = socket.recv(bufsize)
            if not buf:
                return
            infile.write(buf)
    else:
        while size / bufsize > 0:
            buf = socket.recv(bufsize)
            if not buf:
                return
            if len(buf) < bufsize:
                infile.write(buf)
                return
            size -= bufsize
        assert size >=0 and size < bufsize
        if size == 0: return
        buf = socket.recv(size)
        if buf:
            infile.write()
        return

